﻿using Dapper;
using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.DLL.ParametersDLL
{
    public class ParametersBusiness : Base.BaseDLL, IParametersBusiness
    {
        public ParametersBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }

        public decimal GetSeq()
        {
            Parameters Parameters = this.dbConnection.QueryFirstOrDefault<Parameters>("SELECT * FROM Parameters WHERE havedelete=0  ORDER BY autoid DESC LIMIT 0,1");
            if (Parameters is null) return 1;
            else return (Parameters.Sequence is null ? 1 : Parameters.Sequence.Value + 1);
        }

        public List<ParameterValue> GetParametersByCode(string MainCode) => dbConnection.Query<ParameterValue>("SELECT  * FROM parametervalue WHERE maincode=@MainCode", new ParameterValue() { MainCode = MainCode }).AsList();

        public bool IsPermissionCodeRepeat(long AutoId, string Code)
        {
            string sql = $"SELECT * FROM Parameters WHERE code='{Code}'";
            if (AutoId != 0)
            {
                sql = $"{sql} AND autoid != {AutoId}";
            }
            return dbConnection.Query<Parameters>(sql).Any();
        }

        public List<PageParametersTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   AND r.code LIKE '%{queryModel.KeyWord}%' OR r.cnname LIKE '%{queryModel.KeyWord}%' OR r.enname LIKE '%{queryModel.KeyWord}%' ";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "sequence";
                queryModel.IsAsc = false;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (queryModel.ExceptDataField.Any())
            {
                queryModel.ExceptDataField.ForEach(o =>
                {
                    if (!string.IsNullOrEmpty(o.Value + ""))
                        where += $" AND r.{o.Label}!='{o.Value}'";
                });
            }
            if (queryModel.paramters.Any())
            {
                queryModel.paramters.ForEach(p =>
                {
                    if (!string.IsNullOrEmpty(p.Value + ""))
                        where += $"  and  {p.Label} like '%{p.Value}%'  ";
                });
            }
            if (!queryModel.UseDisabledData)
            {
                where += $" AND r.enable=1  ";
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"SELECT count(r.AutoId) as cnt FROM Parameters r WHERE r.havedelete !=1
                        {where}  ;");
            sql.Append(@$"SELECT r.autoId,r.cnname,r.enname,r.code,r.`enable`,r.creator,r.modifier,r.creatdate,r.modifdate FROM Parameters r 
                          WHERE r.havedelete !=1
                        {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{ queryModel.PageSize} ;");
            using (var reader = dbConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageParametersTable> pageModules = reader.Read<PageParametersTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                    RowNo++;
                });
                return pageModules;
            }
        }

        public bool AddParameterValue(string MainCode, List<ParameterValue> values)
        {
            bool b = true;
            dbConnection.Execute("DELETE FROM parametervalue WHERE maincode=@MainCode", new ParameterValue() { MainCode = MainCode });
            if (values != null && values.Any())
            {
                b = dbConnection.Insert(values) >= 0;
            }
            return b;
        }

        public List<ParameterTree> ParameterTrees(string MainCode) => dbConnection.Query<ParameterTree>("select p.code parameterCode,p.cnname parametername,p.enname parameterenname,p.autoid parameterid,p2.autoid valueid,p2.code valuecode,p2.cnname valuename,p2.enname valueenname,p2.`sequence` from parameters p left join parametervalue p2 on p.code=p2.maincode  WHERE p.code=@MainCode and p2.enable=1; ", new ParameterValue() { MainCode = MainCode }).AsList();
    }
}
